﻿using Common;
using DBContext;
using EV.EventBus;
using NLog;
using Seagull.BarTender.PrintServer;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using ZoneLine.Models;
using ZoneLine.Models.PackageModel;
using ZoneLine.Models.PrintRecord;
using ZoneLine.Views;
using ZoneLine.Views.XWStationViews;

namespace ZoneLine
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        public App()
        {
            Process proCurrent = Process.GetCurrentProcess();
            var pros = Process.GetProcesses();
            if (pros == null || pros.Length < 1)
            {
                return;
            }
            if (pros.Count(p => p.ProcessName == proCurrent.ProcessName) > 1)
            {
                //foreach (var pro in pros)
                //{
                //    if (pro.ProcessName == proCurrent.ProcessName)
                //    {
                //        var temp = pro.MainWindowHandle;
                //        //ShowWindow(temp, 0);
                //        //ShowWindow(temp, 1);
                //        //SetForegroundWindow(temp);
                //    }
                //}
                MessageBox.Show("软件已启动，只能同时运行一个软件");
                Environment.Exit(0);
            }
            ThreadPool.SetMinThreads(60, 20);

            ThreadPool.SetMinThreads(60, 20);
            //for (int i = 0; i < 20; i++)
            //{
            //    var index = ProductIndexHelper.GetIndex(ModelEnum.BQKH, 1);
            //    Console.WriteLine(index);
            //}
            if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "HOP.ini"))
            {
                var view = new HStationEnableView();
                Cache.IsHopStaion = true;
                view.Show();
            }
            else if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "XW.ini"))
            {
                var view = new XWStationEnableView();
                Cache.IsXWopStaion = true;
                view.Show();
            }
            else
            {
                var view = new StationEnableView();
                Cache.IsQopStaion = true;
                view.Show();
            }

            this.Exit += App_Exit;
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
        }

        //[DllImport("user32.dll", EntryPoint = "ShowWindow", SetLastError = true)]
        //static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow);

        //[DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        //public static extern bool SetForegroundWindow(IntPtr hWnd);

        private void App_Exit(object sender, ExitEventArgs e)
        {
            DBContext.DbConfig.DbContext.Dispose();
            TaskMaster.Default.Dispose();
        }

        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            var logger = LogManager.GetCurrentClassLogger();
            //task线程内未处理捕获
            MessageBox.Show("捕获线程内未处理异常：" + e.Exception.Message);
            e.SetObserved();//设置该异常已察觉（这样处理后就不会引起程序崩溃）
            logger.Error(e.Exception, "获取未捕捉到的异常");
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs ex)
        {
            var logger = LogManager.GetCurrentClassLogger();
            if (ex.ExceptionObject is System.Exception e)
            {
                logger.Error(e, "未处理的异常！");
                MessageBox.Show(e.Message + e.StackTrace);
            }
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            var logger = LogManager.GetCurrentClassLogger();
            e.Handled = true;
            logger.Error(e.Exception, "未处理的异常！");
            MessageBox.Show(e.Exception.Message + e.Exception.StackTrace);
        }
    }
}